package edu.gdkm.interceptor;

import edu.gdkm.annotation.LoginInterceptor;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FirstInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("----------------------------");
        System.out.println("first interceptor preHandle");
        System.out.println(handler);
        System.out.println("----------------------------");
//        if(request.getRequestURI().indexOf("loginbyuser")>=0){
//            return true;
//        }
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if("login".equals(handlerMethod.getMethod().getName())){
                return true;
            }else {
                if(null!=request.getSession().getAttribute("user")){
                    return true;
                }else{
                    request.setAttribute("msg","你没有权限，请登录后再试!");
                    request.getRequestDispatcher("/login.jsp").forward(request,response);
                    return false;
                }
            }

        }else{
            return true;
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("----------------------------");
        System.out.println("first interceptor postHandle");
        System.out.println(modelAndView);
        System.out.println("----------------------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("----------------------------");
        System.out.println("first interceptor afterCompletion");
        System.out.println(ex);
        if(ex!=null){
            request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request,response);
        }
        System.out.println("----------------------------");
    }
}
